/**
 * Created by lee_mxue on 17/7/31.
 */
import React, { Component, PropTypes } from "react";
import ReactDOM from "react-dom";
import AJAX from "../../lib/ajax";
import Tools from "../../lib/tools";
import Rules from "../../lib/rules";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";
import wx from "wx";
const Toast = require('../MyPackage/components/Toast')

require('../../lib/rem')
require('../../styles/common.less');
require('./PickUpReward.less')
require('../../styles/lux.less')


class TopUp extends Component {
    constructor(props) {
        super(props);
        this.state = {
            changeItem: 'pay1',  //默认两元
            changeCount: '', //充值金额(分)
            pay_style: true,   //勾选充值方式  默认选中
            personal_balance: 0,    //账户余额
        };
        this.changePayItem = this.changePayItem.bind(this);     //选择充值金额
        this.handleInputCount = this.handleInputCount.bind(this);     //输入充值金额
        this.topay = this.topay.bind(this);
        this.wxPay = this.wxPay.bind(this);
        this.selectPayStyle = this.selectPayStyle.bind(this);   //选择支付方式
        this.paySubmit = this.paySubmit.bind(this);
        this.payDialog = this.payDialog.bind(this);     //打赏成功弹窗
    }

    componentWillMount() {
        addErrorListener()()
        //隐藏分享功能
        weixinShare.hideAll();
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
        //    判断打赏支付状态
        //    payState： 支付状态 0:失败； 1: 成功
        var payState = Tools.getParams().payState
        if (payState == 1) {
            //已支付
            var amount = window.localStorage.getItem('PickUpRewardAmount')
            this.payDialog(amount)
        } else {
            //未支付
            window.localStorage.removeItem('PickUpRewardAmount')
        }
    }

    changePayItem(style) {
        this.setState({
            changeItem: style,
        })
    }

    //输入充值金额
    handleInputCount(e) {
        var value = e.target.value;
        // console.log('输入', value)
        if (Rules.payMoney(value)) {
            this.setState({
                changeCount: value
            })
        }
    }

    wxPay(params, cbUrl) {
        const _this = this;
        var order_id = Tools.getParams().order_id
        AJAX.request("get_signature", {
            full_url: window.location.href
        }, (data) => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.body.appid, // 必填，公众号的唯一标识
                timestamp: data.body.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.body.noncestr, // 必填，生成签名的随机串
                signature: data.body.signature,// 必填，签名，见附录1
                jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            })
            wx.ready(() => {
                wx.chooseWXPay({
                    timestamp: params.prepay.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: params.prepay.nonceStr, // 支付签名随机串，不长于 32 位
                    package: params.prepay.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: params.prepay.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: params.prepay.paySign, // 支付签名
                    success: function (res) {
                        // 打赏支付结果回调
                        AJAX.request('tip_pay_query', { serial_num: params.serial_num, order_id: order_id }, (data) => {
                            //trade_status: 交易状态 0:未知状态 13101:下单请求状态 13103:支付完成状态
                            if (data.body.trade_status == 13103) {
                                //成功回调
                                //存入支付金额
                                window.localStorage.setItem('PickUpRewardAmount', params.total_fee)
                                //返回支付选择页面打开成功弹窗
                                //payState： 支付状态 0:失败； 1: 成功
                                cbUrl && location.replace(location.protocol + '//' + location.host + '/' + cbUrl + '?order_id=' + Tools.getParams().order_id + '&payState=1')
                            }
                        })
                    },
                    fail: function () {
                        // 支付失败后的回调函数
                        cbUrl && location.replace(location.protocol + '//' + location.host + '/' + cbUrl + '?order_id=' + Tools.getParams().order_id + '&payState=0')
                    }
                })
            })
        })
    }

    //选择支付方式
    selectPayStyle() {
        this.setState({
            pay_style: !this.state.pay_style
        })
    }


    //支付按钮点击去支付
    topay() {
        if (!this.state.pay_style) {
            this.warn("请选择支付方式");
            return
        }
        switch (this.state.changeItem) {
            case 'pay1':
                this.paySubmit(200)
                break;
            case 'pay2':
                this.paySubmit(500)
                break;
            case 'pay3':
                this.paySubmit(800)
                break;
            case 'pay4':
                this.paySubmit(1800)
                break;
            case 'pay5':
                this.paySubmit(2800)
                break;
            case 'pay6':
                if (!this.state.changeCount || this.state.changeCount === '0') {
                    this.warn("请选择或输入金额");
                    return
                }
                this.paySubmit(parseInt(this.state.changeCount * 100));
                break;
            default:
                this.warn("请选择或输入金额");
                break
        }


    }

    //支付提交-发起打赏
    paySubmit(paycount) {
        var order_id = Tools.getParams().order_id
        AJAX.request('tip_pay_request', { amount: paycount, order_id: order_id }, (data) => {
            const cbUrl = 'PickUpReward'
            if (data.body.prepay) {
                //成功，调用微信支付
                this.wxPay(data.body, cbUrl)
            }
        })
    }

    //成功弹窗
    payDialog(amount) {
        //显示金额
        var showAmount = (amount / 100).toFixed(2);
        var body = window.document.getElementsByTagName('body')[0];
        var existDialog = window.document.getElementById('DialogBox')
        if (!existDialog) {
            //创建弹窗
            var dialog = window.document.createElement('div');
            dialog.setAttribute('id', 'DialogBox');
            dialog.innerHTML = '<div id="mask"></div><div id="content"><i class="number">' + showAmount + '元</i>打赏成功<i class="iconfont icon-cha"></i></div>'
            body.appendChild(dialog)
            //点击遮罩层
            var mask = window.document.getElementById('mask')
            var content = window.document.getElementById('content')
            var icon = content.children[1]
            const wx_type = window.localStorage.getItem('wx_type');
            mask.onclick = function () {
                // _this.topay();
                // window.location.href = `./PickUp?wx_type=${wx_type}`;
                window.location.replace(`./PickUp?wx_type=${wx_type}`);
            }
            icon.onclick = function () {
                // _this.topay();
                // window.location.replace('./PickUp')
                window.location.replace(`./PickUp?wx_type=${wx_type}`);
            }
        } else {
            //删除弹窗
            existDialog.parentNode.removeChild(existDialog)
        }
    }


    //toast弹窗
    warn(content) {
        Toast.warn({
            content: content
        })
    }

    success() {
        Toast.success({
            content: "成功"
        })
    }

    error() {
        Toast.error({
            content: "失败"
        })
    }

    loading() {
        Toast.loading({
            content: "数据加载中"
        })
    }


    render() {

        return (
            <div className="main_diy">
                <div className="balanceBox">
                    <div className="balanceShow">
                        <p className="balanceTitle">赏</p>
                        <p className="balanceNum">打赏快递员</p>
                    </div>
                </div>
                <p className="topUpNumTitle"><span>打赏金额</span></p>
                <ul className="numBox">
                    <li className={`numItem ${this.state.changeItem == 'pay1' ? '' + ' bg_R' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay1')}>
                        2元
                    </li>
                    <li className="gap"></li>
                    <li className={`numItem ${this.state.changeItem == 'pay2' ? '' + ' bg_R' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay2')}>
                        5元
                    </li>
                    <li className="gap"></li>
                    <li className={`numItem ${this.state.changeItem == 'pay3' ? '' + ' bg_R' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay3')}>
                        8元
                    </li>
                </ul>
                <ul className="numBox">
                    <li className={`numItem ${this.state.changeItem == 'pay4' ? '' + ' bg_R' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay4')}>
                        18元
                    </li>
                    <li className="gap"></li>
                    <li className={`numItem ${this.state.changeItem == 'pay5' ? '' + ' bg_R' : +'' + ' bg_G'}`}
                        onClick={this.changePayItem.bind(this, 'pay5')}>
                        18元
                    </li>
                    <li className="gap"></li>
                    <li className='numItem'
                        onClick={this.changePayItem.bind(this, 'pay6')}>
                        <input
                            className={`selfNum ${this.state.changeItem == 'pay6' ? '' + ' bg_R' : +'' + ' bg_G'}`}
                            value={this.state.changeCount} onChange={this.handleInputCount} placeholder="输入任意金额" />
                    </li>
                </ul>
                <p className="payStyle">支付方式</p>
                <div className="payStyleList">
                    <div className="payStyleList_left" onClick={this.selectPayStyle}>
                        <i className="iconfont textGreen icon-iconfontweixin"></i>
                        <span> 微信支付</span>
                    </div>
                    <i className={`payStyleList_right iconfont textYellow ${this.state.pay_style ? '' + 'icon-duigou' : +''}`}></i>
                </div>
                <div className="handleBtnGroup">
                    <a href="javascript:;" onClick={this.topay} className="weui-btn red weui-btn_warn">立即打赏</a>
                </div>
            </div>
        )
    }
}
ReactDOM.render(<TopUp />, document.getElementById('app'))
if (module.hot) {
    module.hot.accept();
}

